<?php
/**
 * Created by PhpStorm.
 * User: poptser
 * Date: 2018/1/22
 * Time: 15:15
 */

namespace App\Services\Sorting;

use App\Services\SortingWeb\OrderService as SortingOrder;
use App\Services\Orders\OrderService as Order;
use App\Services\SortingWeb\ToolService;
use App\Services\Warehouse\WarehouseLocalService;
use http\Exception;
use Illuminate\Support\Facades\DB;

class SortingService{


    public $sortingOrder;   //配货 order service
    public $order;          //主order service
    public $toolService;    //辅助工具 service
    protected $WarehouseLocalService;   //库存相关

    public function __construct(SortingOrder $sortingOrder,Order $order,ToolService $toolService,
                                WarehouseLocalService $warehouseLocalService){

        $this->sortingOrder = $sortingOrder;
        $this->order = $order;
        $this->toolService = $toolService;
        $this->WarehouseLocalService=$warehouseLocalService;

    }
    /**
     * 获取公司列表
     * Author:poptser@foxmail.com
     * @return mixed
     */
    public function getCompanyList(){
        $companyList = DB::table('distribution_company')
            ->select(['id','lite_name'])->get()->toArray();

        $companyList[] = (Object)[
            'id'=>0,
            "lite_name"=>"自配送"
        ];
        return $companyList;
    }

    /**
     * 获取指定区域订单数
     * Author:poptser@foxmail.com
     * @param $date
     * @param null $companyId
     * @param null $time
     * @param null $zone
     * @param  $wid
     * @return mixed
     */
    public function getOrderNum($date=null,$companyId=null, $time=null,
                                $zone=null,$wid){
//        //条件总成
//        $filter = [];
//        $filter[] = ['wid', '=', $wid];
//        $filter[] = ['status', '=', 1]; //未拣货
        $sqlToday = "SELECT COUNT('id') as num FROM sdx_sorting_order WHERE status=1 AND wid=".$wid;
        $sqlOtherday = "SELECT COUNT('id') as num FROM sdx_sorting_order WHERE status=1 AND wid=".$wid;

        if(!empty($companyId)){
            $sqlToday .=" AND company_id = ".$companyId;
            $sqlOtherday .=" AND company_id = ".$companyId;
            //$filter[] = ['company_id', '=', $companyId];
        }
        if(!empty($zone)){
            $sqlToday .=" AND area_id = ".$zone;
            $sqlOtherday .=" AND area_id = ".$zone;
            //$filter[] = ['area_id', '=', $zone];
        }
        if(!empty($time)&&$time!="超时订单"){
            $sqlToday .=" AND best_time = '".$time."'";
            $sqlOtherday .=" AND best_time = '".$time."'";
            //$filter[] = ['best_time', '=', $time];
        }
        if(!empty($date)){
            if($time=="超时订单"){
                $sqlToday .=" AND UNIX_TIMESTAMP(best_date) < ".strtotime($date);
                //$filter[] = ['UNIX_TIMESTAMP("best_date")', '<', strtotime($date)];
            }else{
                $sqlToday .=" AND best_date = '".$date."'";
                //$filter[] = ['best_date', '=', $date];
            }

        }
        //DB::enableQueryLog();
        //$numDate['today'] =  DB::table('sorting_order')->where($filter)->count();
        $todayNum = DB::selectOne($sqlToday);
        //dump($sqlToday);
        $numDate['today'] =  $todayNum->num;
//        dump(DB::getQueryLog());
//        exit();
        if(!empty($date)){
            //array_pop($filter);
            if($time=="超时订单"){
                //$sqlToday .=" AND UNIX_TIMESTAMP(best_date) < ".strtotime($date);
                $sqlOtherday .=" AND UNIX_TIMESTAMP(best_date) >= ".strtotime($date);
                //$filter[] = ['UNIX_TIMESTAMP("best_date")', '<', strtotime($date)];
            }else{
                $sqlOtherday .=" AND best_date != '".$date."'";
                //$filter[] = ['best_date', '=', $date];
            }
            //$filter[] = ['best_date', '<>', $date];
            //$numDate['otherToday'] =  DB::table('sorting_order')->where($filter)->count();
            $otherTodayNum = DB::selectOne($sqlOtherday);
            //dump($sqlOtherday);
            $numDate['otherToday'] =  $otherTodayNum->num;
        }
        return $numDate;

    }

    /**
     * 获取配送时间分组
     * Author:poptser@foxmail.com
     * @param $date
     * @param null $companyId
     * @param null $zone
     * @param $wid
     * @return mixed
     */
    public function getDistributionTime($date,$companyId=null, $zone=null,$wid){
        //条件总成
        $filter = [];
        $filter[] = ['wid', '=', $wid];
        $filter[] = ['status', '=', 1]; //未拣货
        $filter[] = ['best_date', '=', $date];

        if(!empty($companyId)){
            $filter[] = ['company_id', '=', $companyId];
        }
        if(!empty($zone)){
            $filter[] = ['area_id', '=', $zone];
        }
        //DB::enableQueryLog();
        return DB::table('sorting_order')->where($filter)
            ->select(['best_time'])->groupBy('best_time')->get()->toArray();
        //return DB::getQueryLog();
    }

    /**
     * 获取区域列表
     * Author:poptser@foxmail.com
     * @param $date
     * @param null $companyId
     * @param null $time
     * @param $wid
     * @return mixed
     */
    public function getDistributionZone($date, $companyId=null, $time=null,$wid){
        //条件总成
//        $filter = [];
//        $filter[] = ['wid', '=', $wid];
//        $filter[] = ['status', '=', 1]; //未拣货
//        $filter[] = ['best_date', '=', $date];

        $sql = "SELECT area_id FROM sdx_sorting_order WHERE status=1 AND wid=".$wid;

        if(!empty($companyId)){
            $sql .=" AND company_id = ".$companyId;
            //$filter[] = ['company_id', '=', $companyId];
        }
        if(!empty($time)&&$time!="超时订单"){
            $sql .=" AND best_time = '".$time."'";
            //$filter[] = ['best_time', '=', $time];
        }
        if($time=="超时订单"){
            $sql .=" AND UNIX_TIMESTAMP(best_date) < ".strtotime($date);
        }else{
            $sql .=" AND best_date = '".$date."'";
        }
        //DB::enableQueryLog();
//        $ZoneList = DB::table('sorting_order')->where($filter)
//            ->select(['area_id'])->groupBy('area_id')->get()->toArray();
        $sql .=" group by area_id";

        $ZoneList = DB::select($sql);
        //dump($sql);
        foreach ($ZoneList as $value){
            //转换区域名称
            $value->name = $this->toolService->getAreaName($value->area_id);
        }
        return $ZoneList;
        //return DB::getQueryLog();
    }

    /**
     * 获取一个拣货单
     * Author:poptser@foxmail.com
     * @param $date
     * @param $companyId
     * @param $time
     * @param $zone
     * @param $wid
     * @return mixed
     */
    public function getSortingOrder($date, $companyId, $time, $zone, $wid){
        //条件总成
//        $filter = [];
//        $filter[] = ['wid', '=', $wid];
//        $filter[] = ['status', '=', 1]; //未拣货
//        $filter[] = ['best_date', '=', $date];
//        $filter[] = ['area_id', '=', $zone];
//        $filter[] = ['best_time', '=', $time];
//        $filter[] = ['company_id', '=', $companyId];
//        //return $filter;
//        $sortingOrder = DB::table('sorting_order')->where($filter)
//            ->orderBy('id')->first();

        $sql = "SELECT * FROM sdx_sorting_order WHERE status=1 AND wid=".$wid." AND area_id=".$zone." AND company_id = ".$companyId;

        if($time=="超时订单"){
            $sql .=" AND UNIX_TIMESTAMP(best_date) < ".strtotime($date);
        }else{
            $sql .=" AND best_time = '".$time."' AND best_date = '".$date."'";
        }
        $sql .=" ORDER BY id DESC LIMIT 1";

        $sortingOrder = DB::select($sql);

        return $sortingOrder;
    }

    /**
     * 设置拣货单状态
     * Author:poptser@foxmail.com
     * @param $sortingId
     * @param $status
     * @param $userId
     * @return bool
     */
    public function setSortingStatus($sortingId, $status,$userId){
        //判定状态
        switch ($status){
            case 1:
                $data['status'] = 1; //未拣货
                $data['sorting_user'] = 0;
                $data['start_time'] = 0;
                break;
            case 2:
                $data['status'] = 2; //已获取
                $data['receive_time'] = gm_time();
                break;
            case 3:
                $data['status'] = 3; //拣货中
                $data['start_time'] = gm_time();
                $data['sorting_user'] = $userId;
                break;
            case 4:
                $data['status'] = 4; //已拣货
                $data['complete_time'] = gm_time();
                break;
            case 5:
                $data['status'] = 5; //已取消
                break;
            default:
                return false;
        }

        if(!empty($data)){
            //新版拣货单方式
            $judgment = DB::table('sorting_order')->where('id', $sortingId)->update($data);
            if(!empty($judgment)){
                return true;
            }else{
                DB::rollBack();
                return false;
            }
        }

    }

    /**
     * 修改订单状态
     * Author:poptser@foxmail.com
     * @param $orderId
     * @param $status
     * @param $userId
     * @return bool
     */
    public function setOrderStatus($orderId, $status,$userId){
        switch ($status){
            case 1:
                $data['shipping_status'] = 0; //取消配货
                $data['sorting_time'] = 0; //取消配货
                $data['sorting_id'] = 0; //取消配货
                $statusDescription = "取消配货";
                $shippingstatus = 0;
                break;
            case 2:
                break;
            case 3:
                $data['shipping_status'] = 3; //配货中
                $data['sorting_id'] = $userId;
                $statusDescription = "开始配货";
                $shippingstatus = 3;
                break;
            case 4:
                $data['shipping_status'] = 5; //配货完成
                $data['sorting_time'] = gm_time(); //配货完成时间
                $statusDescription = "完成配货";
                $shippingstatus = 5;
                break;
            case 5:
                break;
            default:
                return false;
        }

        if(!empty($data)){
            //DB::enableQueryLog();
            $judgment = DB::table('order_info')->where('order_id',"=", $orderId)
                ->update($data);
            //return DB::getQueryLog();
            if($judgment==1){
                //插入订单记录,写入物流记录
                $orderStatus = $this->sortingOrder->getOrderStatus($orderId);
                $dataAction['order_status'] = $orderStatus->order_status;
                $dataAction['shipping_status'] = $orderStatus->shipping_status;
                $dataAction['pay_status'] = $orderStatus->pay_status;
                $dataAction['action_user'] = $this->toolService->getNameById($userId);
                $dataAction['order_id']=$orderId;
                $dataAction['action_note']=$statusDescription." [ SortingApp ]";;
                $dataAction['log_time']=gm_time();
                $dataAction['user_id']=$userId;
                $this->order->addOrderAction($dataAction);
                $this->toolService->recordLogistics($orderId,$shippingstatus,$statusDescription);
                return true;
            }else{
                return false;
                DB::rollBack();
                //user_error("这是一个自定义的错误");
            }
        }
    }

    /**
     * 获取问题商品数量
     * Author:poptser@foxmail.com
     * @param $orderId
     * @param $goodsSn
     * @return \Illuminate\Database\Eloquent\Model|null|object|static
     */
    public function getQuestionGood($orderId, $goodsSn){
        $filter = [];
        $filter[] = ['order_id', '=', $orderId];
        $filter[] = ['goods_sn', '=', $goodsSn]; //未拣货
        return DB::table("order_goods")->where($filter)->first(['lackNum','poorNum']);
    }

    /**
     * 获取拣货单详情
     * Author:poptser@foxmail.com
     * @param $sortingId
     * @param $kindeeSn /金蝶编号
     * @param $wid /金蝶编号
     * @return array
     */
    public function getSortingOrderInfo($sortingId,$kindeeSn = false,$wid=null){
        $sortingOrderIdList = $this->sortingOrder->getOrderBySorting($sortingId);
        $OrderGoods = [];
        foreach ($sortingOrderIdList as $key=>$value){
            $orderGoods = $this->order->getGoodsList($value);
            foreach ($orderGoods as $good){

//                $goodsNum = $good['goods_number']-$good['refund_number']
//                    -$good['poorNum']-$good['lackNum'];
                $goodsNum = $good['goods_number']-$good['refund_number'];

                //获取问题商品
                $questionGoods = $this->getQuestionGood($value,$good['goods_sn']);

                if(!empty($OrderGoods[$good['goods_id']])){
                    if($goodsNum>0){
                        $OrderGoods[$good['goods_id']]['goodsNum'] +=$goodsNum;
                        $orderInfo = [
                            "orderId"=>$value,
                            "orderSn"=>$this->toolService->getOrderSn($value),
                            "orderNum"=>$goodsNum,
                            "poorNum"=>$questionGoods->poorNum,
                            "lackNum"=>$questionGoods->lackNum,
                            "SortingNum"=>$key+1,
                        ];
                        array_push($OrderGoods[$good['goods_id']]['orderList'],
                            $orderInfo);
                    }
                }else{
                    if($goodsNum>0){
                        $orderInfo = [
                            "orderId"=>$value,
                            "orderSn"=>$this->toolService->getOrderSn($value),
                            "orderNum"=>$goodsNum,
                            "poorNum"=>$questionGoods->poorNum,
                            "lackNum"=>$questionGoods->lackNum,
                            "SortingNum"=>$key+1,
                        ];
                    }else{
                        $orderInfo = null;
                    }

                    $goodsInfo = DB::table("goods")->where("goods_sn",$good['goods_sn'])
                        ->select(['goods_img','cat_id','goods_sn','supplier_code as k3_supplier_sn','consignment as k3_vmi'])
                        ->first();
                    //return $goodsInfo->goods_img;
//
                    if($kindeeSn!==false){
                        $goodsToKingdee = [];
                        $goodsToKingdee[$goodsInfo->goods_sn] = [
                            "goods_sn"=>$goodsInfo->goods_sn,
                            "k3_vmi"=>$goodsInfo->k3_vmi,
                            "k3_supplier_sn"=>$goodsInfo->k3_supplier_sn,
                        ];

                        $jindeeData =$this->WarehouseLocalService->CheckGoodsUsableWarehouse($goodsToKingdee,$wid);

//                        dump($jindeeData);
//                        exit();
                        if($jindeeData){
                            $goodsInventory = (int)$jindeeData[$goodsInfo->goods_sn];
                        }else{
                            $goodsInventory = "无库存记录";
                        }

                        //$goodsInventory = 0;
                    }else{
                        $goodsInventory = 0;    //不显示库存
                    }
                    if($wid>0){
                        $goodsShelf =  $this->getGoodsShelf($good['goods_sn'],$wid);
                    }else{
                        $goodsShelf['shelf_info'] = null;
                        $goodsShelf['shelf_sort'] = null;
                        $goodsShelf['areaId'] = null;
                        $goodsShelf['areaList'] = null;
                    }

                    $favourableInfo = unserialize($good['favourable_info']);

                    //return $favourableInfo['gift'];

                    if(empty($favourableInfo['gift'])){
                        $favourableInfo['gift'][0]['id'] = null;
                    }

                    $OrderGoods[$good['rec_id']] = [
                        "goodsSn"=>$good['goods_sn'],
                        "goodsId"=>$good['goods_id'],
                        "goodsImg"=>$goodsInfo->goods_img,
                        "goodsClass"=>DB::table("category")->where("cat_id",$goodsInfo->cat_id)->value("cat_name"),
                        "goodsName"=>$good['goods_name'],
                        "goodsNum"=>$goodsNum,
                        "goodsAddress"=>$goodsShelf['shelf_info'],
                        "goodsSort"=>$goodsShelf['shelf_sort'],
                        "areaId"=>$goodsShelf['areaId'],
                        "areaList"=>$goodsShelf['areaList'],
                        "goodsInventory"=>$goodsInventory,
                        "goodsGive"=>$good['giving'],
                        "goodsActionGoodsId"=>$favourableInfo['gift'][0]['id'],
                        "orderList"=>[ $orderInfo ]
                        ];
                }
            }

        }


        //重组结构
        $newGoodsList = [];
        foreach ($OrderGoods as $goods){
            $orderList = [];
            foreach ($goods['orderList'] as $order){
                $orderList[] = $order;
            }
            if($goods['goodsNum']>0){
                $newGoodsList[] = [
                    "goodsSn"=>$goods['goodsSn'],
                    "goodsImg"=>$goods['goodsImg'],
                    "goodsClass"=>$goods['goodsClass'],
                    "goodsInventory"=>$goods['goodsInventory'],
                    "goodsName"=>$goods['goodsName'],
                    "goodsNum"=>$goods['goodsNum'],
                    "goodsAddress"=>$goods['goodsAddress'],
                    "goodsSort"=>$goods['goodsSort'],
                    "areaId"=>$goods['areaId'],
                    "goodsId"=>$goods['goodsId'],
                    "goodsGive"=>$goods['goodsGive'],
                    "areaList"=>$goods['areaList'],
                    "goodsActionGoodsId"=>$goods['goodsActionGoodsId'],
                    "orderList"=>$orderList
                ];
            }
        }

        $newOrderInfo['orderNum'] = count($sortingOrderIdList); //订单数
        $newOrderInfo['goodsType'] = count($newGoodsList); //商品种类
        $newOrderInfo['goodsList'] = $newGoodsList; //商品详情

        if($kindeeSn!==false){
            $goodsArea = DB::table("shelves_cat")->select("id","name")->get(); //仓库区域对照表
            foreach ($goodsArea as $key=>$value){
                $value->goodsNum = 0;
                foreach ($newGoodsList as $keys=>$value2){
                    if(is_array($value2['areaList'])){
                        if(in_array($value->id,$value2['areaList'])){
                            $value->goodsNum ++;
                        }
                    }

                }
            }
            $newOrderInfo['goodsArea'] = $goodsArea;
        }

        return $newOrderInfo;
    }

    /**
     * 获取商品货架信息
     * Author:poptser@foxmail.com
     * @param $goodSn
     * @param $wid
     * @param bool $returnArray
     * @return mixed
     */
    public function getGoodsShelf($goodSn, $wid, $returnArray = false){
        //货架信息
        $sql = "SELECT sc.id AS areaId,sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,sh.shelves_sn AS shelf_num FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg WHERE sh.state = 1 AND sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id AND sh.wid = '".$wid."' AND sg.goods_sn = '".$goodSn."'";
        $goods_shelves = DB::select($sql);


        if($goods_shelves){
            $shelf = [];
            $areaList = [];
            foreach ($goods_shelves as $vaule){
                if($returnArray){
                    $shelf['shelf_info'][] = $vaule->shelf_tag."->".$vaule->shelf_type."[ ".$vaule->shelf_num."-".$vaule->putaway_row." ]";
                }else{
                    $areaList[] = $vaule->areaId;
                    if(empty($shelf['shelf_info'])){
                        $shelf['shelf_info'] = $vaule->shelf_tag."->".$vaule->shelf_type."[ ".$vaule->shelf_num."-".$vaule->putaway_row." ]";
                    }else{
                        $shelf['shelf_info'] .= $vaule->shelf_tag."->".$vaule->shelf_type."[ ".$vaule->shelf_num."-".$vaule->putaway_row." ]";
                    }

                }
                $shelf['shelf_sort'] = $vaule->sort+$vaule->putaway_row/100;
            }
            $shelf['areaId'] = implode(",",array_unique($areaList));
            $shelf['areaList'] = array_unique($areaList);
        }else{
            $shelf['shelf_info'] = "未找到货架信息";
            $shelf['shelf_sort'] = 0;
            $shelf['areaId'] = 0;
            $shelf['areaList'] = null;
        }

        return $shelf;
    }

    /**
     * 设置次品缺货状态
     * Author:poptser@foxmail.com
     * @param $goodsDate
     * @param $userId
     * @return bool
     */
    public function setSortingOrderOdd($goodsDate,$userId){
        foreach ($goodsDate as $order){
            $thisOrderStatus = 0;
            $kackStatus = false;
            $poorStatus = false;
            $orderGoods = $this->order->getGoodsList($order['orderId']);

            foreach ($order['goodsList'] as $key=>$goods){
                if($goods['lackNum']>0){
                    //此商品缺货
                    $kackStatus = true;
                    foreach ($orderGoods as $dbGoods){
                        if($dbGoods['goods_sn'] == $goods['goodsSn']){
                            $lastNum = $dbGoods['goods_number'] - $dbGoods['refund_number'];
                            if($lastNum < $goods['lackNum']){
                                return $goods['goodsSn']." 仅剩余：".$lastNum;
                            }else{
                                $order['goodsList'][$key]['goodsName'] = $dbGoods['goods_name'];
                            }
                        }
                    }
                }
                if($goods['poorNum']>0){
                    //此商品次品
                    $poorStatus = true;
                    foreach ($orderGoods as $dbGoods){
                        if($dbGoods['goods_sn'] == $goods['goodsSn']){
                            $lastNum = $dbGoods['goods_number'] - $dbGoods['refund_number'];
                            if($lastNum < $goods['poorNum']){
                                return $goods['goodsSn']." 仅剩余：".$lastNum;
                            }else{
                                $order['goodsList'][$key]['goodsName'] = $dbGoods['goods_name'];
                            }
                        }
                    }
                }
            }

            if($kackStatus=== true && $poorStatus === true){
                $thisOrderStatus = 3;
            }
            if($kackStatus=== true && $poorStatus === false){
                $thisOrderStatus = 1;
            }
            if($kackStatus=== false && $poorStatus === true){
                $thisOrderStatus = 2;
            }

            if($thisOrderStatus != 0){
                //return 11;
                $statusDescription = "问题单提交:<br/>";
                foreach ($order['goodsList'] as $goods){
                    $updateDate['poorNum'] = $goods['poorNum'];
                    $updateDate['lackNum'] = $goods['lackNum'];
                    //DB::enableQueryLog();
                    DB::table('order_goods')->where([
                        ["order_id","=",$order['orderId']],
                        ["goods_sn","=",$goods['goodsSn']],
                    ])->update($updateDate);
                    //return DB::getQueryLog();
                    $statusDescription .=$goods['goodsName']." 缺:".$updateDate['lackNum']." 次:".$updateDate['poorNum']."<br/>";

                }

                DB::table('order_info')->where([
                    ["order_id","=",$order['orderId']]
                ])->update([
                    'freeze_status' => $thisOrderStatus,
                    'freeze_time' => gm_time(),
                    'freeze_id' => $userId,
                ]);

                //脱离原拣货单
                //$this->sortingOrder->removeSortingOrder($order['orderId']);


                $orderStatus = $this->sortingOrder->getOrderStatus($order['orderId']);
                $dataAction['order_status'] = $orderStatus->order_status;
                $dataAction['shipping_status'] = $orderStatus->shipping_status;
                $dataAction['pay_status'] = $orderStatus->pay_status;
                $dataAction['action_user'] = $this->toolService->getNameById($userId);
                $dataAction['order_id']=$order['orderId'];
                $dataAction['action_note']=$statusDescription." [ SortingApp ]";;
                $dataAction['log_time']=gm_time();
                $dataAction['user_id']=$userId;
                $this->order->addOrderAction($dataAction);
            }

        }
        return true;
    }
    /**
     * 设置拣货单状态
     * Author:poptser@foxmail.com
     * @param $sortingId
     * @param $userId
     * @param $status 1未开始 2已获取 3开始配货 4完成拣货
     * @return bool
     * @throws \Exception
     */

    public function setSortingOrderStatus($sortingId, $userId, $status){
        //修改已配货完成
        try{
            DB::beginTransaction();
            $setRue = $this->setSortingStatus($sortingId,$status,$userId);  //拣货单已完成
            if($setRue){
                $sortingOrderIdList = $this->sortingOrder->getOrderBySorting($sortingId);

                foreach ($sortingOrderIdList as $value){
                    $this->setOrderStatus($value,$status,$userId);    //订单配货完成
                }
                if($status == 1){
                    //退回拣货单/删除拣货单相关信息
                    DB::table('sorting_order')->where('id', $sortingId)->delete();
                    DB::table('sorting_order_link')->where('sorting_order_id', $sortingId)->delete();
                }
            }else{
                return "不支持的类型";
            }
            DB::commit();
            return true;
        }catch (Exception $exception){
            return $exception->getMessage();
        }


    }
    /**
     * 获取已配货完成历史
     * Author:poptser@foxmail.com
     * @param $showDate
     * @param $userId
     * @return mixed
     */
    public function getSortingHistory($showDate,$userId,$wid){
        //条件总成
        $filter = [];
        //
        $filter[] = ['wid', '=', $wid];
        $filter[] = ['sorting_user', '=', $userId];
        $filter[] = ['status', '=', 4];


        //DB::enableQueryLog();
        $sortingData =  DB::table('sorting_order')
            ->where($filter)
            ->whereBetween('complete_time', [strtotime($showDate), strtotime($showDate." 23:29:59")])
            ->select(['sorting_sn as sortingSn','id as sortingId','status','area_id'])
            ->orderBy('complete_time','desc')
            ->get();
        //return DB::getQueryLog();
        $ToolService =  new ToolService();
        $orderNum = 0;
        foreach ($sortingData as $value){
            $sortingOrderIdList = $this->sortingOrder->getOrderBySorting($value->sortingId);
            $value->goodsNum = $this->sortingOrder->getGoodsNumByOrder($sortingOrderIdList);
            $value->orderNum = count($sortingOrderIdList);
            $value->status = $this->toolService->sortingToString($value->status);
            $value->zone = $ToolService->getAreaName($value->area_id);
            $orderNum +=$value->orderNum;
        }
        $listData['sortingList'] = $sortingData;
        $listData['sortingNum'] = count($sortingData);
        $listData['orderNum'] = $orderNum;
        return $listData;
    }

    /**
     * 拣货中列表
     * Author:poptser@foxmail.com
     * @param $userId
     * @param $wid
     * @param $toNum
     * @return \Illuminate\Support\Collection
     */
    public function getSortingIng($userId, $wid,$toNum = false){
        //条件总成
        $filter = [];
        //
        $filter[] = ['wid', '=', $wid];
        $filter[] = ['sorting_user', '=', $userId];
        $filter[] = ['status', '=', 3];

        if($toNum){
            return DB::table('sorting_order')
                ->where($filter)
                ->count();
        }
        //DB::enableQueryLog();
        $sortingData =  DB::table('sorting_order')
            ->where($filter)
            ->select(['sorting_sn as sortingSn','id as sortingId','status','area_id'])->get();
        //return $sortingData;
        //return DB::getQueryLog();
        $ToolService =  new ToolService();
        foreach ($sortingData as $value){
            $sortingOrderIdList = $this->sortingOrder->getOrderBySorting($value->sortingId);
            $value->goodsNum = $this->sortingOrder->getGoodsNumByOrder($sortingOrderIdList);
            $value->orderNum = count($sortingOrderIdList);
            $value->status = $this->toolService->sortingToString($value->status);
            $value->zone = $ToolService->getAreaName($value->area_id);
        }
        return $sortingData;
    }


    /**
     * 获取待质检订单数
     * Author:poptser@foxmail.com
     * @param $wid
     * @return int
     */
    public function getUnQualityNum($wid){
        //条件总成
        $filter = [];
        //
        $filter[] = ['wid', '=', $wid];
        $filter[] = ['shipping_id', '=', 3];
        $filter[] = ['order_status', '<>', 2];
        $filter[] = ['shipping_status', '=', 5];    //配货完成
        $filter[] = ['freeze_status', '=', 0];      //未冻结
        $filter[] = ['quality_id', '=', 0];         //未质检

        return DB::table('order_info')
            ->whereIn('pay_status', [2, 3])
            ->where($filter)
            ->count();

    }

    /**
     * 获取拣货单，以订单方式，打印用
     * Author:poptser@foxmail.com
     * @param $sortingId
     * @return array
     */
    public function getSortingOrderPrint($sortingId){
        $sortingOrderIdList = $this->sortingOrder->getOrderBySorting($sortingId);
        $orderInfo = [];
        foreach ($sortingOrderIdList as $key=>$value){
            $orderGoods = $this->order->getGoodsList($value);
            $oneOrderGoods = [];
            foreach ($orderGoods as $good){
                $oneOrderGoods[] = [
                    "goodsSn"=>$good['goods_sn'],
                    "goodsName"=>$good['goods_name'],
                    "discountPrice"=>$good['discount_price'],
                    "goodsPrice"=>$good['goods_price'],
                    "goodsNum"=>$good['goods_number']-$good['refund_number']
                ];
            }
            $orderInfoOne = $this->order->getOrderById($value,['wdr_id','best_time','best_time_start',
                'sorting_id','sorting_time','order_id']);

            $orderAreaInfo = $this->toolService->getDeliver($orderInfoOne['wdr_id']);
            $oneOrder =[
                "orderId"=>$value,
                "sortingNum"=>$key+1,
                "sortingSn"=>$this->toolService->getSortingSn($sortingId),
                "orderArea"=>$this->toolService->getAreaName($orderAreaInfo->zoning_id)."-".$orderAreaInfo->name,
                "sortingName"=>$this->toolService->getNameById($orderInfoOne['sorting_id']),
                "sortingTime"=>local_date("Y-m-d H:i:s",$orderInfoOne['sorting_time']),
                "bestTime"=>$this->toolService->bestToStr($orderInfoOne['best_time_start'],$orderInfoOne['best_time']),
                "orderSn"=>$this->toolService->getOrderSn($value),
                "goodsInfo"=>$oneOrderGoods
            ];
            $orderInfo[] = $oneOrder;
        }
        return $orderInfo;
    }
    /**
     * 获取指定时间段内完成配货的订单数
     * @param null $startTime
     * @param null $endTime
     * @param $userId
     * @return mixed
     */
    public function gerCompleteOrderNumByDate($startTime=null, $endTime=null,$userId){

        $filter = [];
        $filter[] = ['sorting_id', '=', $userId];
        $filter[] = ['order_status', '<>', 2]; //未取消
        $filter[] = ['196_admin_id', '=', 0];   //非196订单



        $orderNum =  DB::table('order_info')
            ->where($filter)
            ->whereIn('pay_status', [2, 3])
            ->whereBetween('sorting_time', [$startTime-28801, $endTime-28799])
            ->count();
        return $orderNum;
    }
}